#!/usr/bin/python3.8
# coding:utf-8
# zabbix钉钉告警脚本(带图片)

import requests
import pymysql
import re
import datetime
import json
import sys

class zabbix(object):
    def __init__(self, message, user, token):
        self.message = message
        self.user = user
        self.token = token
        # 存放监控图形的目录
        self.dir = '/tmp/zabbix_media/'
        self.time = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
        self.image_name = "zabbix_" + self.time + ".jpg"
        self.login_url = 'http://zabbix.local.com/index.php'
        self.login_data = {
            'name': 'admin',
            'password': 'admin',
            'autologin': 1,
            'enter': 'Sign in'
        }
        self.login_headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
            'Referer': self.login_url
        }
        # 数据库连接
        self.mysql = {
            'host': 'localhost',
            'username': 'root',
            'password': '123456',
            'port': 3306
        }

    def get_itemid(self):
        pattern = re.compile('ITEMID:(\d+)', re.S)
        itmeid = re.findall(pattern, self.message)
        return str(itmeid[0])

    def get_graphid(self):
        itemid = self.get_itemid()
        conn = pymysql.connect(host=self.mysql['host'],
                               user=self.mysql['username'],
                               password=self.mysql['password'],
                               port=self.mysql['port'],
                               db='zabbix'
                               )
        cur = conn.cursor()
        cur.execute('SELECT graphid FROM `graphs_items` WHERE itemid=%s' % itemid)
        graphid = cur.fetchone()
        cur.close()
        conn.close()
        return graphid[0]

    def get_image(self):
        graphid = self.get_graphid()
        # 登陆zabbix
        myRequests = requests.Session()
        try:
            myRequests.post(self.login_url, self.login_data, self.login_headers)
            UrlplayLoad = {
                "from": "now-10m",
                "to": "now",
                "itemids": graphid,
                "width": "700",
            }
            img_url = 'http://zabbix.local.com/chart2.php?graphid=%s&isNow=1&profileIdx=web.graphs&width=800&height=350' % graphid
            img = myRequests.get(img_url)
            if img.status_code == 200:
                with open(self.dir + self.image_name, 'wb') as f:
                    f.write(img.content)
        except Exception as e:
            print(e)

    def send_message(self):
        data = {
            "msgtype": "actionCard",
            "actionCard": {
                "title": "Zabbix告警通知",
                "text": f"####  告警通知 \n\n ![screenshot](http://nginx.local.com/images/{self.image_name}) "
                        "\n\n" + self.message,
                "hideAvatar": "0",
                "btnOrientation": "0",
                "btns": [
                    {
                        "title": "查看详情",
                        "actionURL": "http://zabbix.local.com/zabbix.php?action=dashboard.view"
                    },
                ],
            }
        }
        webhook = "https://oapi.dingtalk.com/robot/send?access_token={}".format(self.token)
        headers = {'Content-Type': 'application/json'}
        try:
            req = requests.post(url=webhook, data=json.dumps(data), headers=headers)
            print(req.status_code)
        except Exception as e:
            print(e)


if __name__ == '__main__':
    message = sys.argv[1]
    user = sys.argv[2]
    token = sys.argv[3]
    Zabbix = zabbix(message, user, token)
    Zabbix.get_image()
    Zabbix.send_message()
